package com.shamine.kuaiqiao.blink.detail

import android.content.Context
import android.content.Intent
import android.net.Uri
import cn.bmob.v3.BmobQuery
import cn.bmob.v3.BmobUser
import cn.bmob.v3.datatype.BmobFile
import cn.bmob.v3.exception.BmobException
import cn.bmob.v3.listener.DownloadFileListener
import cn.bmob.v3.listener.UpdateListener
import cn.bmob.v3.listener.UploadFileListener
import com.shamine.kuaiqiao.blink.data.Gallery
import com.shamine.kuaiqiao.blink.data.Photo
import com.shamine.kuaiqiao.blink.event.EventSavePhoto
import com.shamine.kuaiqiao.blink.events.EventPhotoUpload
import com.shamine.kuaiqiao.blink.tools.DateTool
import com.shamine.kuaiqiao.blink.basic.BlinkApplication
import com.shamine.kuaiqiao.blink.data.Passer
import com.shamine.kuaiqiao.blink.event.EventGalleryDeleted
import com.shamine.kuaiqiao.blink.events.EventPhotoDeleted
import com.shamine.kuaiqiao.blink.events.EventPhotos
import org.greenrobot.eventbus.EventBus
import rx.Subscriber
import java.io.File

class Worker(val context: Context,val gallery: Gallery) {

    private lateinit var query: BmobQuery<Photo>
    /**
     * 获取相册列表
     */
    fun getPhotos(virgin: Boolean,date: String) {
        query = BmobQuery()
        if (!virgin) query.addWhereLessThan("createdAt", DateTool().getBmobDate(date))
        query.setLimit(18)
        query.order("-createdAt")
        query.include("passer")
        query.include("photo")
        query.include("gallery")
        query.addWhereEqualTo("gallery",gallery)
        query.addWhereEqualTo("passer", BmobUser.getCurrentUser())
        query.findObjectsObservable(Photo::class.java).subscribe(object: Subscriber<List<Photo>>(){
            override fun onNext(list: List<Photo>?) {
                EventBus.getDefault().post(EventPhotos(true,list!!.toMutableList()))
            }

            override fun onCompleted() {
            }

            override fun onError(p0: Throwable?) {
                EventBus.getDefault().post(EventPhotos(false,p0?.message.toString()))
            }

        })
    }

    /**
     * 上传照片
     */
    fun upload(path: String?) {
        val file = BmobFile(File(path))
        //1.上传照片
        file.upload(object : UploadFileListener() {
            override fun done(e: BmobException?) {
                if (e == null) {
                    //2.关联到相册
                    val photo = Photo(gallery,BmobUser.getCurrentUser(Passer::class.java),file)
                    photo.saveObservable().subscribe(object : Subscriber<String>() {
                        override fun onCompleted() {
                        }
                        override fun onError(throwable: Throwable) {
                            EventBus.getDefault().post(EventPhotoUpload(false, throwable.message.toString()))
                        }
                        override fun onNext(objectId: String) {
                            val tempGallery = Gallery(gallery.size + 1,false)
                            tempGallery.update(gallery.objectId,object: UpdateListener(){
                                override fun done(p0: BmobException?) {
                                    if (p0==null){
                                        gallery.size = tempGallery.size
                                        EventBus.getDefault().post(EventPhotoUpload(true, photo,gallery.size))
                                    } else EventBus.getDefault().post(EventPhotoUpload(false, p0.message.toString()))
                                }
                            })
                        }
                    })
                } else {
                    EventBus.getDefault().post(EventPhotoUpload(false, e.message.toString()))
                }
            }
        })
    }

    /**
     * 删除相册
     */
    fun deleteGallery(gallery: Gallery) {
        val theGallery = Gallery(true)
        theGallery.update(gallery.objectId,object: UpdateListener(){
            override fun done(p0: BmobException?) {
                if (p0 == null)
                    EventBus.getDefault().post(EventGalleryDeleted(true,""))
                else
                    EventBus.getDefault().post(EventGalleryDeleted(false,p0.message.toString()))
            }
        })
    }

    /**
     * 删除照片
     */
    fun deletePhoto(photo: Photo) {
        val dyingPhoto = Photo(BmobUser.getCurrentUser(Passer::class.java))
        val tempGallery = Gallery(gallery.size-1,false)
        dyingPhoto.delete(photo.objectId,object : UpdateListener(){
            override fun done(e: BmobException?) {
                if (e==null){
                    //删除照片成功
                    tempGallery.update(gallery.objectId,object : UpdateListener(){
                        override fun done(p0: BmobException?) {
                            if (p0 ==null){
                                //更新成功
                                gallery.size = tempGallery.size
                                EventBus.getDefault().post(EventPhotoDeleted(true,gallery.size))
                            } else EventBus.getDefault().post(EventPhotoDeleted(false,p0.message.toString()))
                        }
                    })
                } else EventBus.getDefault().post(EventPhotoDeleted(false,e.message.toString()))
            }

        })
    }

    /**
     * 保存指定照片
     * 权限
     */
    fun savePhoto(photo: Photo) {
        photo.photo.download(File(BlinkApplication.SAVE_PATH,"${photo.createdAt}.jpg")
                ,object: DownloadFileListener(){
            override fun onProgress(p0: Int?, p1: Long) {
            }

            override fun done(p0: String?, p1: BmobException?) {
                if (p1==null){
                    EventBus.getDefault().post(EventSavePhoto(true,""))
                    //通知系统相册更新
                    val uri = Uri.fromFile(File(BlinkApplication.SAVE_PATH,"${photo.createdAt}.jpg"))
                    context.sendBroadcast(Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri))
                }else EventBus.getDefault().post(EventSavePhoto(true,p1.message.toString()))
            }
        })
    }
}